package com.futao.springboot.learn.api.jmeter;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author futao@gmail.com
 * @date 2021/12/16
 */
@RestController
@RequestMapping
public class LoginController {

    private static final Map<String, String> USER_MAP = new HashMap<>();

    /**
     * 登录
     *
     * @param mobile
     * @param response
     * @return
     */
    @PostMapping("/login")
    public boolean login(@RequestParam("mobile") String mobile, HttpServletResponse response) {
        String cookie = UUID.randomUUID().toString();
        USER_MAP.put(cookie, mobile);
        response.addCookie(new Cookie("token", cookie));
        return true;
    }

    /**
     * 获取用户信息
     *
     * @param request
     * @return
     */
    @GetMapping("/user-info")
    public String userInfo(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    return USER_MAP.get(cookie.getValue());
                }
            }
        }
        return "请先登录";
    }
}
